package com.joysuccess.queue.strategy;

import com.joysuccess.common.utils.SpringUtil;
import com.joysuccess.queue.core.ProducerStrategy;
import com.joysuccess.queue.core.QueuePropertiesHandler;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author : zhangqing
 * @Description: rabbitmq 抽象类
 * @date : 2020年06月09日 17:12
 */
public class RabbitProducerStrategy implements ProducerStrategy<Connection> {

    /**
     * 单例模式：懒汉模式
     */
    private static volatile RabbitProducerStrategy instance;

    public static RabbitProducerStrategy getInstance() {
        if(instance == null){
            synchronized (RabbitProducerStrategy.class){
                if(null == instance){
                    instance = new RabbitProducerStrategy();
                }
            }
        }
        return instance;
    }

    @Override
    public void sendRecordToQueue(String queueName,String data) {
        Channel channel =null;
        Connection connection = getProducerClient();
        try {
            channel = connection.createChannel();
            channel.queueDeclare(queueName,false,false,false,null);
            channel.basicPublish("",queueName,null,data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                channel.close();
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Connection getProducerClient() {
        QueuePropertiesHandler queuePropertiesHandler = SpringUtil.getBean(QueuePropertiesHandler.class);

        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(queuePropertiesHandler.getUserName());
        factory.setPassword(queuePropertiesHandler.getPassword());
        factory.setHost(queuePropertiesHandler.getHost());
        factory.setPort(queuePropertiesHandler.getPort());
        Connection conn = null;
        try {
            conn = factory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}
